<template>
  <div class="space-y-6">
    <!-- 页面标题和操作 -->
    <div class="flex justify-between items-center">
      <h2 class="text-2xl font-bold text-gray-900">普通用户管理</h2>
      <el-button type="primary" @click="showAddDialog">
        <i class="fas fa-plus mr-2"></i>
        添加用户
      </el-button>
    </div>

    <!-- 搜索筛选 -->
    <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
      <el-form :model="searchForm" inline>
        <el-form-item label="用户名">
          <el-input v-model="searchForm.username" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="searchForm.email" placeholder="请输入邮箱" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="正常" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <i class="fas fa-search mr-2"></i>
            搜索
          </el-button>
          <el-button @click="resetSearch">
            <i class="fas fa-redo mr-2"></i>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 用户列表 -->
    <div class="bg-white rounded-lg shadow-sm border border-gray-200">
      <el-table
        :data="userList"
        v-loading="loading"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column label="头像" width="80">
          <template #default="{ row }">
            <el-avatar :size="40" :src="getImageUrl(row.avatar)">
              <i class="fas fa-user"></i>
            </el-avatar>
          </template>
        </el-table-column>
        <el-table-column prop="username" label="用户名" width="120"/>
        <el-table-column prop="real_name" label="真实姓名" width="120"/>
        <el-table-column prop="email" label="邮箱" width="200"/>
        <el-table-column prop="phone" label="手机号" width="120"/>
        <el-table-column label="性别" width="80">
          <template #default="{ row }">
            <span v-if="row.gender === 1">男</span>
            <span v-else-if="row.gender === 2">女</span>
            <span v-else>未设置</span>
          </template>
        </el-table-column>
        <el-table-column label="账户余额" width="120">
          <template #default="{ row }">
            <span class="text-green-600 font-medium">¥{{ row.balance || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="注册时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="320" fixed="right" align="center">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="showEditDialog(row)">
              <i class="fas fa-edit mr-1"></i>
              编辑
            </el-button>
            <el-button type="info" size="small" @click="viewUserDetail(row)">
              <i class="fas fa-eye mr-1"></i>
              详情
            </el-button>
            <el-button
              size="small"
              :type="row.status === 1 ? 'warning' : 'success'"
              @click="toggleUserStatus(row)"
            >
              <i :class="row.status === 1 ? 'fas fa-ban mr-1' : 'fas fa-check mr-1'"></i>
              {{ row.status === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button type="danger" size="small" @click="deleteUser(row)">
              <i class="fas fa-trash mr-1"></i>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="flex justify-center py-4">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      :title="isEdit ? '编辑用户' : '添加用户'"
      v-model="dialogVisible"
      width="600px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="userForm"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="userForm.username"
            placeholder="请输入用户名"
            @blur="checkUsername"
          />
        </el-form-item>
        <el-form-item label="真实姓名" prop="real_name">
          <el-input v-model="userForm.real_name" placeholder="请输入真实姓名" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="userForm.gender">
            <el-radio :label="0">未设置</el-radio>
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="生日" prop="birthday">
          <el-date-picker
            v-model="userForm.birthday"
            type="date"
            placeholder="请选择生日"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="账户余额" prop="balance">
          <el-input-number
            v-model="userForm.balance"
            :min="0"
            :precision="2"
            placeholder="请输入账户余额"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="userForm.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="!isEdit" label="密码" prop="password">
          <el-input v-model="userForm.password" type="password" placeholder="请输入密码" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 用户详情对话框 -->
    <el-dialog
      title="用户详情"
      v-model="detailDialogVisible"
      width="800px"
    >
      <div v-if="selectedUser" class="space-y-4">
        <div class="grid grid-cols-2 gap-4">
          <div class="space-y-2">
            <p><strong>用户ID:</strong> {{ selectedUser.id }}</p>
            <p><strong>用户名:</strong> {{ selectedUser.username }}</p>
            <p><strong>真实姓名:</strong> {{ selectedUser.real_name || '未设置' }}</p>
            <p><strong>邮箱:</strong> {{ selectedUser.email }}</p>
            <p><strong>手机号:</strong> {{ selectedUser.phone || '未设置' }}</p>
          </div>
          <div class="space-y-2">
            <p><strong>性别:</strong> 
              <span v-if="selectedUser.gender === 1">男</span>
              <span v-else-if="selectedUser.gender === 2">女</span>
              <span v-else>未设置</span>
            </p>
            <p><strong>生日:</strong> {{ selectedUser.birth_date || '未设置' }}</p>
            <p><strong>账户余额:</strong> <span class="text-green-600 font-medium">¥{{ selectedUser.balance || 0 }}</span></p>
            <p><strong>状态:</strong> 
              <el-tag :type="selectedUser.status === 1 ? 'success' : 'danger'">
                {{ selectedUser.status === 1 ? '正常' : '禁用' }}
              </el-tag>
            </p>
            <p><strong>注册时间:</strong> {{ selectedUser.create_time }}</p>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { adminAPI } from '@/api/admin.js'
import { authAPI } from '@/api/auth.js'

const loading = ref(false)
const dialogVisible = ref(false)
const detailDialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref()
const selectedUser = ref(null)

const searchForm = reactive({
  username: '',
  email: '',
  status: '',
  role_id: 3 // 固定为普通用户角色ID
})

const userForm = reactive({
  id: null,
  username: '',
  real_name: '',
  email: '',
  phone: '',
  gender: 0,
  birthday: '',
  balance: 0,
  status: 1,
  password: '',
  role_id: 3 // 固定为普通用户角色ID
})

const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

const userList = ref([])

// 自定义用户名验证器
const validateUsername = async (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入用户名'))
    return
  }
  if (value.length < 3 || value.length > 20) {
    callback(new Error('用户名长度在 3 到 20 个字符'))
    return
  }

  // 编辑模式下，如果用户名没有改变，不需要检查
  if (isEdit.value && value === userForm.username) {
    callback()
    return
  }

  try {
    const response = await authAPI.checkUsername(value)
    if (!response.data) {
      callback(new Error('用户名已存在'))
    } else {
      callback()
    }
  } catch (error) {
    console.error('检查用户名失败:', error)
    callback()
  }
}

const formRules = {
  username: [
    { validator: validateUsername, trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ]
}

// 获取图片URL
const getImageUrl = (url) => {
  if (!url) return ''

  // 如果是完整的URL，直接返回
  if (url.startsWith('http')) {
    return url
  }

  // 如果是上传的文件路径
  if (url.startsWith('/uploads/')) {
    return `http://localhost:8081/api${url}`
  }

  // 如果是静态资源路径
  if (url.startsWith('/assets/')) {
    return `http://localhost:8081/api${url}`
  }

  // 其他情况，添加API前缀
  return `/api${url}`
}

const loadUserList = async () => {
  loading.value = true
  try {
    const params = {
      current: pagination.currentPage,
      size: pagination.pageSize,
      ...searchForm
    }

    const response = await adminAPI.getUserList(params)
    userList.value = response.data.records || []
    pagination.total = response.data.total || 0
  } catch (error) {
    console.error('加载用户列表失败:', error)
    ElMessage.error('加载用户列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.currentPage = 1
  loadUserList()
}

const resetSearch = () => {
  Object.assign(searchForm, {
    username: '',
    email: '',
    status: '',
    role_id: 3
  })
  handleSearch()
}

const formatDate = (dateString) => {
  if (!dateString) return '-'
  try {
    const date = new Date(dateString)
    if (isNaN(date.getTime())) return '-'
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
  } catch (error) {
    console.error('日期格式化错误:', error)
    return '-'
  }
}

const showAddDialog = () => {
  isEdit.value = false
  dialogVisible.value = true
}

const showEditDialog = (row) => {
  isEdit.value = true
  Object.assign(userForm, { ...row })
  dialogVisible.value = true
}

const viewUserDetail = (row) => {
  selectedUser.value = row
  detailDialogVisible.value = true
}

const resetForm = () => {
  Object.assign(userForm, {
    id: null,
    username: '',
    real_name: '',
    email: '',
    phone: '',
    gender: 0,
    birthday: '',
    balance: 0,
    status: 1,
    password: '',
    role_id: 3
  })
  formRef.value?.resetFields()
}

const checkUsername = async () => {
  if (!userForm.username || isEdit.value) return

  try {
    const response = await authAPI.checkUsername(userForm.username)
    if (!response.data) {
      ElMessage.warning('用户名已存在，请更换其他用户名')
    }
  } catch (error) {
    console.error('检查用户名失败:', error)
  }
}

const submitForm = async () => {
  try {
    await formRef.value.validate()

    if (isEdit.value) {
      await adminAPI.updateUser(userForm.id, userForm)
      ElMessage.success('用户更新成功')
    } else {
      await adminAPI.createUser(userForm)
      ElMessage.success('用户添加成功')
    }

    dialogVisible.value = false
    resetForm()
    loadUserList()
  } catch (error) {
    console.error('操作失败:', error)

    // 处理特定的错误信息
    let errorMessage = '操作失败'
    if (error.message) {
      if (error.message.includes('Duplicate entry') && error.message.includes('uk_username')) {
        errorMessage = '用户名已存在，请更换其他用户名'
      } else if (error.message.includes('Duplicate entry') && error.message.includes('email')) {
        errorMessage = '邮箱已存在，请更换其他邮箱'
      } else {
        errorMessage = error.message
      }
    }

    ElMessage.error(errorMessage)
  }
}

const toggleUserStatus = async (row) => {
  try {
    const action = row.status === 1 ? '禁用' : '启用'
    await ElMessageBox.confirm(`确定要${action}用户 "${row.username}" 吗？`, '确认操作')

    const newStatus = row.status === 1 ? 0 : 1
    await adminAPI.toggleUserStatus(row.id, newStatus)
    row.status = newStatus
    ElMessage.success(`用户${action}成功`)
  } catch (error) {
    if (error !== 'cancel') {
      console.error('操作失败:', error)
      ElMessage.error(error.message || '操作失败')
    }
  }
}

const deleteUser = async (row) => {
  try {
    await ElMessageBox.confirm(`确定要删除用户 "${row.username}" 吗？`, '确认删除', {
      type: 'warning'
    })

    await adminAPI.deleteUser(row.id)
    ElMessage.success('用户删除成功')
    loadUserList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error(error.message || '删除失败')
    }
  }
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  loadUserList()
}

const handleCurrentChange = (page) => {
  pagination.currentPage = page
  loadUserList()
}

onMounted(() => {
  loadUserList()
})
</script>
